<template>
  <div class="settlement">
    <div class="plus"></div>
    <van-nav-bar title="订单结算" left-text="返回" left-arrow @click-left="goBack" class="nav-bar" />
    <div class="box">
      <div class="content">
        <div class="address">
          <div @click="selectAddress" class="select">选择地址<i></i></div>
          <div v-if="defaultAddress" class="contact">
            <div class="name">{{defaultAddress.name}}</div>
            <div class="phone">{{defaultAddress.tel}}</div>
            <div v-show="defaultAddress.checked" class="default">默认</div>
          </div>
          <div v-if="defaultAddress" class="location">{{defaultAddress.province}}{{defaultAddress.city}}{{defaultAddress.county}}{{defaultAddress.addressDetail}}</div>
        </div>
        <div class="order-info">
          <div class="title">订单信息</div>
          <div class="product">
            <ProList v-for="item in productList" :key="item.sid" :proData="item">
              <div class="count" slot="count">x{{item.count}}</div>
            </ProList>
          </div>
          <div class="total">
            <div class="number">共计<span>{{number}}</span>件</div>
            <div class="price">合计<span>&yen;</span>{{price}}</div>
          </div>
        </div>
      </div>
      <div class="button">
        <van-button round color="#ff594d" block @click="pay">立即结算</van-button>
      </div>
    </div>
    <van-popup class="addressList" v-model="showAddress" position="bottom" closeable>
      <div class="title">选择地址</div>
      <AdsList showCheckbox @changeAddress="changeAddress" />
      <van-button round color="#ff594d" block @click="addAddress">新增地址</van-button>
    </van-popup>
    <van-popup class="pay" v-model="showPay" position="bottom" closeable>
      <div class="title">支付密码</div>
      <!-- 密码输入框 -->
      <van-password-input :value="password" :gutter="10" :focused="showKeyboard" @focus="showKeyboard = true" :error-info="errorInfo" />
      <!-- 数字键盘 -->
      <van-number-keyboard v-model="password" :show="showKeyboard" :maxlength="6" @blur="showKeyboard = false" :hide-on-click-outside="false" />
    </van-popup>
  </div>
</template>

<script>
import ProList from "@/components/ProList.vue";
import AdsList from "@/components/AdsList.vue";

export default {
  name: "Settlement",

  components: {
    ProList,
    AdsList,
  },

  data() {
    return {
      // 商品sid
      sids: "",
      // 商品数据
      productList: [],
      // 选择地址
      showAddress: false,
      // 初始化地址
      defaultAddress: [],
      // 确认支付层
      showPay: false,
      // 密码
      password: "",
      // 输入框聚焦
      showKeyboard: true,
      // 密码错误提示
      errorInfo: "",
    };
  },

  created() {
    // 获取传递过来的商品sid
    this.sids = this.$route.query.sids;

    // 获取订单商品列表
    this.getProductList();

    // 获取默认商品地址
    this.getDefaultAddress();
  },

  computed: {
    // 计算订单中商品总数量
    number() {
      let count = 0;
      this.productList.forEach((v) => {
        count += v.count;
      });
      return count;
    },
    // 计算订单中商品总价格
    price() {
      let count = 0;
      this.productList.forEach((v) => {
        count += v.count * v.price;
      });
      return count;
    },
  },

  methods: {
    // 点击顶部左边按钮返回上一页
    goBack() {
      this.$router.go(-1);
    },

    // 获取订单商品列表
    getProductList() {
      // 获取token
      let tokenString = this.$cookies.get("TOKEN");
      // 获取传递过来的商品sid
      let sids = this.sids;

      // 如果非法进入此页面则自动跳转到购物袋页面
      if(!this.sids) {
        // 设置导航栏当前索引值
        this.$util.setSessionItem("tabbarActive", 2);
        this.$router.replace({ name: "Shopping" });
        return;
      }
      // 处理sids格式
      sids = JSON.stringify(sids.split("-"));
      // 
      this.axios
        .get("commitShopcart", {
          params: {
            tokenString,
            sids,
          },
        })
        .then((res) => {
          // 
          let data = res.data;
          if (data.code === 50000 && data.result.length > 0) {
            this.productList = data.result;
          } else if (data.code === 50000 && data.result.length == 0) {
            // 设置导航栏当前索引值
            this.$util.setSessionItem("tabbarActive", 2);
            // 如果结算后未能跳转到订单页面则自动跳转到购物袋页面
            this.$router.replace({ name: "Shopping" });
          }
        })
        .catch((err) => {
          
        });
    },

    // 显示选择地址弹出层
    selectAddress() {
      this.showAddress = true;
    },

    // 新增地址
    addAddress() {
      this.$router.push({ name: "NewAddress" });
    },

    // 获取默认商品地址
    getDefaultAddress() {
      let tokenString = this.$cookies.get("TOKEN");
      this.axios
        .get("findAddress", {
          params: {
            tokenString,
          },
        })
        .then((res) => {
          // 
          if (res.data.code == 700) {
            this.$toast("请先登录");
            // 清除token
            this.$cookies.remove("TOKEN");
            // 延迟2秒后跳转到登录页面
            let timer = setTimeout(() => {
              clearTimeout(timer);
              this.$router.replace({ name: "Login" });
            }, 2000);
            return;
          }
          if (res.data.code === 20000) {
            // 定义选中标记
            let none = true;
            // 循环查找默认地址
            for (let index in res.data.result) {
              // 如果找到默认地址就赋值给初始化地址
              if (res.data.result[index].isDefault) {
                // 添加初始选中状态
                res.data.result[index].checked = true;
                this.defaultAddress = res.data.result[index];
                none = false;
                return;
              }
            }
            // 如果没有默认地址，则设置地址列表里第一个为初始化地址
            if (none) {
              this.defaultAddress = res.data.result[0];
            }
          }
        })
        .catch((err) => {
          
        });
    },

    // 改变选中地址
    changeAddress(aid) {
      // 如果地址跟原地址相同,则不进行改变
      if (this.defaultAddress.aid === aid) {
        // 将选择地址弹出层隐藏
        this.showAddress = false;
        return;
      }
      let tokenString = this.$cookies.get("TOKEN");
      this.axios
        .get("findAddress", {
          params: {
            tokenString,
          },
        })
        .then((res) => {
          // 
          if (res.data.code == 700) {
            this.$toast("请先登录");
            // 清除token
            this.$cookies.remove("TOKEN");
            // 延迟2秒后跳转到登录页面
            let timer = setTimeout(() => {
              clearTimeout(timer);
              this.$router.replace({ name: "Login" });
            }, 2000);
            return;
          }
          if (res.data.code === 20000) {
            // 循环查找子组件传递的地址aid
            for (let index in res.data.result) {
              // 如果找到默认地址就赋值给初始化地址
              if (res.data.result[index].aid === aid) {
                // 添加初始选中状态
                if (res.data.result[index].isDefault) {
                  res.data.result[index].checked = true;
                }
                // 更改订单地址信息
                this.defaultAddress = res.data.result[index];
                // 并且将选择地址弹出层隐藏
                this.showAddress = false;
                return;
              }
            }
          }
        })
        .catch((err) => {
          
        });
    },

    // 立即结算（模拟支付）
    pay() {
      // 如果未选择地址则不能提交
      if (!this.defaultAddress) {
        this.$toast("请选择地址");
        return;
      }
      this.$dialog
        .confirm({
          title: "提示",
          message: "是否确认提交订单？",
        })
        .then(() => {
          // 点击确认唤起支付界面（模拟支付）
          this.showPay = true;
        })
        .catch(() => {
          
        });
    },
  },

  watch: {
    // 模拟支付验证
    password(value) {
      if (value.length === 6) {
        if (value == "123456") {
          let tokenString = this.$cookies.get("TOKEN");
          // 商品id列表
          let sids = this.sids;
          sids = JSON.stringify(sids.split("-"));
          // 手机号
          let phone = this.defaultAddress.tel;
          // 收货地址
          let address =
            this.defaultAddress.province +
            this.defaultAddress.city +
            this.defaultAddress.county +
            this.defaultAddress.addressDetail;
          // 收货人
          let receiver = this.defaultAddress.name;
          // 发起结算请求
          this.axios
            .post("pay", {
              tokenString,
              sids,
              phone,
              address,
              receiver,
            })
            .then((res) => {
              // 
              if (res.data.code == 700) {
                this.$toast("请先登录");
                // 清除token
                this.$cookies.remove("TOKEN");
                // 延迟2秒后跳转到登录页面
                let timer = setTimeout(() => {
                  clearTimeout(timer);
                  this.$router.replace({ name: "Login" });
                }, 2000);
                return;
              }
              if (res.data.code === 60000) {
                this.$toast(res.data.msg);
                // 收起支付层
                this.showPay = false;
                // 设置导航栏当前索引值
                this.$util.setSessionItem("tabbarActive", 3);
                // 延迟2秒后跳转到订单页面
                let timer = setTimeout(() => {
                  clearTimeout(timer);
                  this.$router.push({ name: "Order" });
                }, 2000);
              }
            })
            .catch((err) => {
              
            });
        } else {
          this.errorInfo = "密码错误";
          this.password = "";
        }
      }
    },

    // 当确认支付层变化时,清空密码输入框的值和错误提示
    showPay() {
      this.password = "";
      this.errorInfo = "";
    },
  },
};
</script>

<style lang="less" scoped>
.van-nav-bar {
  /deep/.van-icon {
    color: #ffa341;
  }
  /deep/.van-nav-bar__text {
    color: #ffa341;
  }
  /deep/.van-nav-bar__title {
    color: #333;
  }
}

.box {
  position: absolute;
  top: 46px + 28px;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  padding: 10px;
  color: #333;
  .content {
    flex: 1;
    padding-bottom: 10px;
    overflow-x: hidden;
    overflow-y: auto;
    .address {
      padding: 12px;
      background: #fff;
      color: #666;
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      .select {
        display: flex;
        align-items: center;
        padding-bottom: 10px;
        color: #333;
        font-weight: bold;
        i {
          display: inline-block;
          margin-left: 5px;
          width: 6px;
          height: 6px;
          border-top: 1.5px solid #333;
          border-right: 1.5px solid #333;
          transform: rotate(45deg);
        }
      }
      .contact {
        display: flex;
        align-items: center;
        margin: 3px 0;
        height: 20px;
        .name {
          margin-top: -3px;
          color: #ff594d;
          font-weight: bold;
        }
        .phone {
          margin: 0 20px;
        }
        .default {
          padding: 2px 8px;
          background: #ff594d;
          color: #fff;
          border-radius: 20px;
        }
      }
      .location {
        color: #999;
      }
    }
    .order-info {
      margin-top: 10px;
      padding: 12px;
      background: #fff;
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      .product {
        padding-bottom: 15px;
        .count {
          color: #999;
        }
      }
      .total {
        position: relative;
        display: flex;
        padding-top: 15px;
        border-top: 1px dashed #d4d4d4;
        &::after,
        &::before {
          position: absolute;
          top: -9px;
          display: block;
          width: 18px;
          height: 18px;
          background: #f7f8fa;
          border-radius: 100%;
          content: "";
        }
        &::after {
          left: -20px;
        }
        &::before {
          right: -20px;
        }
        .price {
          margin-left: auto;
          color: #ff594d;
          font-size: 13px;
          font-weight: bold;
        }
        span {
          padding: 0 3px;
        }
      }
    }
  }
}
.addressList {
  padding: 20px 15px;
  color: #333;
  font-size: 14px;
  box-sizing: border-box;
  .title {
    margin-top: -2px;
    margin-bottom: 15px;
    font-weight: bold;
  }
}
.pay {
  padding: 20px 15px;
  height: 350px + 18px;
  color: #333;
  font-size: 14px;
  box-sizing: border-box;
  .title {
    margin-top: -2px;
    margin-bottom: 10px;
    text-align: center;
    font-weight: bold;
  }
  /deep/ .van-password-input__error-info,
  .van-password-input__info {
    margin-top: 0;
    font-size: 12px;
  }
}
</style>